package com.czk.practice.client;

import com.czk.practice.codec.Decoder;
import com.czk.practice.codec.Encoder;
import com.czk.practice.domain.Message1;
import com.czk.practice.domain.Message2;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/8/19 15:23
 */
public class Client {
    public static void main(String[] args) {
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(workerGroup);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.AUTO_READ, true);
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel channel) throws Exception {
                    ChannelPipeline pipeline = channel.pipeline();
                    pipeline.addLast(new Encoder());
                    pipeline.addLast(new Decoder());
                    pipeline.addLast(new MyClientHandler());
                }
            });
            ChannelFuture f = b.connect("localhost", 7379).sync();
            System.out.println("客户端启动成功");
            System.out.println("客户端发送消息");
            // 测试消息，分别发放demo01、demo02、demo03
            Message1 message1 = new Message1();
            message1.setContent("msg1".getBytes());
            message1.setLen(message1.getContent().length);
            Message2 message2 = new Message2();
            message2.setContent("msg2啊".getBytes());
            message2.setLen(message2.getContent().length);
           // f.channel().writeAndFlush(message1);
            f.channel().writeAndFlush(message2);
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }
}
